var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/TreeSelect/hooks/useLazyTreeSelect.ts
var useLazyTreeSelect_exports = {};
__export(useLazyTreeSelect_exports, {
  default: () => useLazyTreeSelect
});
module.exports = __toCommonJS(useLazyTreeSelect_exports);
var import_react = require("react");
var import_FieldContext = require("../../_utils/contexts/FieldContext");
var import_hooks = require("@szzj/hooks");
function useLazyTreeSelect({
  loadTreeData,
  value,
  fieldNames,
  loadNodeDetail,
  loadTreeDataBySearch
}) {
  const { value: valueKey = "value", children: childrenKey = "children" } = fieldNames || {};
  const { label } = (0, import_FieldContext.useFieldContext)();
  const [initialTreeData, setInitialTreeData] = (0, import_react.useState)([]);
  const [expandedKeys, setExpandedKeys] = (0, import_react.useState)([]);
  const [treeNodesBySearch, setTreeNodesBySearch] = (0, import_react.useState)(
    []
  );
  const [searchExpandedKeys, setSearchExpandedKeys] = (0, import_react.useState)([]);
  (0, import_react.useEffect)(() => {
    loadTreeData().then((data) => {
      setInitialTreeData(data);
    });
  }, [loadTreeData]);
  const { treeNodes, append, findNode, findAncestorNodes, filter, toArray } = (0, import_hooks.useTree)(initialTreeData, {
    uniqueKey: valueKey,
    childrenKey
  });
  (0, import_react.useEffect)(() => {
    if (treeNodes.length) {
      setExpandedKeys(treeNodes.map((node) => node[valueKey]));
    }
  }, [treeNodes.length]);
  const loadDataByPatentCode = (0, import_react.useCallback)(
    (selectedOptions) => {
      var _a;
      const targetTreeNode = selectedOptions;
      if (((_a = targetTreeNode[childrenKey]) == null ? void 0 : _a.length) > 0 || targetTreeNode.isLeaf) {
        return Promise.resolve(void 0);
      }
      return new Promise((resolve) => {
        loadTreeData(targetTreeNode).then((opts) => {
          opts.forEach(async (item) => {
            append({ ...item }, targetTreeNode[valueKey]);
          });
          resolve(void 0);
        });
      });
    },
    [loadTreeData, append, treeNodes]
  );
  const [nodeDetail, setNodeDetail] = (0, import_react.useState)(void 0);
  const fetchDeptNodeDetail = () => {
    loadNodeDetail == null ? void 0 : loadNodeDetail(value).then((res) => {
      setNodeDetail(res);
    });
  };
  (0, import_react.useEffect)(() => {
    if (value && !findNode(value)) {
      fetchDeptNodeDetail();
    }
  }, [value]);
  (0, import_react.useEffect)(() => {
    const loadDeptNodesByDetail = async () => {
      if ((initialTreeData == null ? void 0 : initialTreeData.length) > 0 && nodeDetail) {
        const codePaths = nodeDetail.split("/");
        const firstIndex = codePaths.findIndex((item) => !findNode(item));
        if (firstIndex > 0 && findNode(codePaths[firstIndex - 1])) {
          await loadDataByPatentCode({ [valueKey]: codePaths[firstIndex - 1] });
        }
      }
    };
    loadDeptNodesByDetail();
  }, [initialTreeData, nodeDetail, findNode]);
  const handleSearch = (0, import_react.useCallback)(
    (searchValue) => {
      if (searchValue && loadTreeDataBySearch) {
        loadTreeDataBySearch(searchValue).then((res) => {
          setTreeNodesBySearch(res);
          setSearchExpandedKeys(
            toArray(filter(res, (itemNode) => {
              var _a;
              return !itemNode.isLeaf && ((_a = itemNode == null ? void 0 : itemNode.children) == null ? void 0 : _a.length) > 0;
            })).map(
              (item) => item[valueKey]
            )
          );
        });
      } else if (!searchValue) {
        setTreeNodesBySearch([]);
        setSearchExpandedKeys([]);
      }
    },
    [loadTreeDataBySearch]
  );
  (0, import_react.useEffect)(() => {
    if (value) {
      const ancestorNodes = findAncestorNodes(value);
      const keysToFill = ancestorNodes.filter(
        (node) => {
          var _a;
          return ((_a = node.children) == null ? void 0 : _a.length) > 0 && !node.isLeaf && !expandedKeys.some((key) => node[valueKey] === key);
        }
      ).map((node) => node[valueKey]);
      setExpandedKeys([...expandedKeys, ...keysToFill]);
    }
  }, [value, findAncestorNodes]);
  return {
    label,
    valueKey,
    childrenKey,
    treeNodes,
    loadDataByPatentCode,
    handleSearch,
    treeNodesBySearch,
    setTreeNodesBySearch,
    searchExpandedKeys,
    expandedKeys,
    setExpandedKeys,
    value
  };
}
